package com.sh.suhe.utildemos.utils.http;

import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 统一提供数据提交的方法
 *
 * @author suhe
 */
public class SendFactorynew {
    public static SendFactorynew sendFactory;
    private Charset chatSet = Charset.forName("UTF-8");
    private long outTime = 10 * 60 * 1000;

    public static SendFactorynew getInstance() {
        if (sendFactory == null) {
            synchronized (SendFactorynew.class) {
                return new SendFactorynew();
            }
        }
        return sendFactory;
    }


    /**
     *
     * @author 作者:苏和
     *
     *上传文件
     * @param 参数描述
     * @return 返回值描述
     * @throws <异常类型> {@inheritDoc}
     */

    /**
     * Spring post
     * 上传数据信息，采用post方式
     */
    public String getByOkHttp(Map<String, Object> data, String url){
        String result="";
        Set<String> sets = data.keySet();
        for(String set :sets){
            if (url.contains("?")){
                url += "&" +set+"="+ data.get(set);
            }else {
                url += "?" +set+"="+ data.get(set);
            }
        }
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

//    /**
//     *
//     * post
//     * @param data
//     * @return 返回值描述
//     * @throws <异常类型> {@inheritDoc}
//     * @author 作者:苏和
//     * http 发送数据
//     */
//    public String sendByOkHttp(Map<String, Object> data, String url) {
//        String result = "";
//        try {
//            PostFormBuilder builder = OkHttpUtils.post();
//
//            Map<String, String> headers = new HashMap<String, String>();
//
//            if ( MapUtils.isNotEmpty(data)) {
//                Set<String> sets = data.keySet();
//                for (String key : sets) {
//                    String value =  MapUtils.getString(data, key);
//                    if (!TextUtils.isEmpty(value)) {
//                        File file = null;
//                        try {
//                            file = new File(value);
//                        } catch (Exception e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                        if (file != null && file.exists()) {//文件
//                            headers.put("APP-Key", "APP-Secret222");
//                            headers.put("APP-Secret", "APP-Secret111");
//                            String[] temp = value.split("/");
//                            String fileName = temp[temp.length - 1];
//                            builder.addFile(key, fileName, file);
//                        } else {//普通文本
//                            builder.addParams(key, value);
//                        }
//                    } else {
//                        builder.addParams(key, value);
//                    }
//                }
//            }
//            builder.url(url);//
//            if ( MapUtils.isNotEmpty(headers)) {
//                builder.headers(headers);//
//            }
//            Response respose = builder.build().connTimeOut(outTime)
//                    .writeTimeOut(outTime)
//                    .readTimeOut(outTime)
//                    .execute();
//            result = respose.body().string();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        return result;
//    }
    /**
     *
     * post
     * @param data
     * @return 返回值描述
     * @throws <异常类型> {@inheritDoc}
     * @author 作者:苏和
     * http 发送数据
     */
    public NetResult sendByOkHttp(String url, Map<String, Object> data) {
        NetResult result = new NetResult();
        try {
            FormBody.Builder builder = new FormBody.Builder();
                Set<String> sets = data.keySet();
                for (String key : sets) {
                    String value = (String) data.get( key);
                    if (TextUtils.isEmpty(value)){
                        value = "";
                    }
                    builder.add(key, value);
                }

            Request requset = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();
            OkHttpClient okHttpClient = new OkHttpClient();

            Response response = okHttpClient.newCall(requset)
                    .execute();
           int code = response.code();
           String json = response.body().string();
           if (code == HttpURLConnection.HTTP_OK){
               result.setResCode(1);
           }else {
               result.setResCode(2);
           }
            result.setResult(json);

        } catch (Exception e) {
            e.printStackTrace();
            result.setResCode(2);
            result.setResult("请求异常");
        }
        return result;
    }
    public NetResult uploadImgs(String url, Map<String, Object> data, List<String> pathList){
        NetResult result = new NetResult();
        OkHttpClient client = new OkHttpClient.Builder()
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        try {
            MediaType MutilPart_Form_Data = MediaType.parse("image/png");
//            RequestBody bodyParams = RequestBody.create(MutilPart_Form_Data, GsonUtils.toJson(data));
            MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);

            Set<String> sets = data.keySet();
            for (String key : sets) {
                String value = (String) data.get( key);
                    requestBodyBuilder.addFormDataPart(key,   value);

            }
            //循环添加文件
            for (int i = 0; i < pathList.size(); i++) {
                File file = new File(pathList.get(i));
                requestBodyBuilder.addFormDataPart("files", file.getName(), RequestBody.create(MutilPart_Form_Data, file));
            }
            RequestBody requestBody = requestBodyBuilder.build();
            Request request = new Request.Builder()
                    .url( url)
                    .post(requestBody)
                    .build();
            Response respose = client.newCall(request).execute();
            int code = respose.code();
            String json = respose.body().string();
            if (code == HttpURLConnection.HTTP_OK){
                result.setResCode(1);
            }else {
                result.setResCode(2);
            }
            result.setResult(json);
        } catch (IOException e) {
            e.printStackTrace();
            result.setResCode(2);
            result.setResult("请求异常");
        }
        return result;

    }


    public static void main(String[] args) {
        Map<String, Object> upData = new HashMap<String, Object>();
        upData.put("method", "execute");
        upData.put("action", "getAllPlanList");
    }
    /**
     * 返回SD卡的根路径，如果没有路径返回 ""
     *
     * @return
     */
    public static String getSDCardRootPath() {
        String path = "";
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath();
            // path = Environment.getExternalStorageDirectory().getPath();
        } else {
            path = ""; // filePath: /data/data/
        }

        return path;
    }
}
